package com.company.cloud.behavior.modules.app.controller;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.company.cloud.behavior.modules.api.response.CollectionSearchModel;
import com.company.cloud.behavior.modules.api.response.UserSimpleForBehavior;
import com.company.cloud.behavior.modules.app.controller.req.FollowIsUserParam;
import com.company.cloud.behavior.modules.base.entity.UserFollowInfo;
import com.company.cloud.common.asserts.ValidatorUtils;
import com.company.cloud.common.bean.BaseClientResult;
import com.company.cloud.user.modules.api.response.UserSimple;
import com.company.cloud.user.modules.api.service.UserRemoteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.cloud.behavior.modules.app.controller.req.FollowQuery4PageParam;
import com.company.cloud.behavior.modules.app.controller.req.FollowSaveParam;
import com.company.cloud.behavior.modules.base.entity.UserThumbsUpInfo;
import com.company.cloud.behavior.modules.base.service.UserThumbsUpInfoService;
import com.company.cloud.behavior.modules.cache.models.BehaviorSearchModel;
import com.company.cloud.behavior.modules.cache.service.BehaviorCacheService;
import com.company.cloud.behavior.modules.cache.utils.BehaviorConvertUtils;
import com.company.cloud.common.auth.annotation.Login;
import com.company.cloud.common.bean.BaseResult;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.bean.LoginUserInfo;
import com.company.cloud.common.constant.BaseConstant;
import com.company.cloud.common.constant.BaseReturnEnum;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.common.utils.AuthContextUtils;
import com.company.cloud.common.utils.CheckUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 点赞
 */
@Login
@RestController
@RequestMapping("/app/behavior/thumbsUp")
@Api(tags="App_Behavior_点赞服务")
public class ThumbsUpController {

	@Autowired
	private UserThumbsUpInfoService userThumbsUpInfoService;
	@Autowired
	private BehaviorCacheService behaviorCacheService;
	@Autowired
	private UserRemoteService userRemoteService;

	@PostMapping("/query")
	@ApiOperation(value="点赞列表查询", response= BehaviorSearchModel.class)
	public BaseResult query(@RequestBody FollowQuery4PageParam params) {
		LoginSimpleUserInfo userInfo= AuthContextUtils.getUser();
		IPage<UserThumbsUpInfo> page = userThumbsUpInfoService.page(new Page<>(params.getPage(), params.getRows()),
				new QueryWrapper<UserThumbsUpInfo>()
						.eq("user_id", userInfo.getId())
						.eq(StrUtil.isNotEmpty(params.getObjType()), "obj_type", params.getObjType())
						.eq(StrUtil.isNotEmpty(params.getObjNo()),"obj_no",params.getObjNo())
						.eq("rows_state", BaseConstant.EnabledEnum.ENABLED.getCode())
						.orderByDesc("cdt")
		);


		if(page==null || CollUtil.isEmpty(page.getRecords())){
			return BaseResult.ok();
		}


		Set<Integer> userIds=new HashSet<>();
		page.getRecords().forEach(item->{
			userIds.add(item.getUserId());
		});
		BaseClientResult<Map<Integer, UserSimple>>  userResult=userRemoteService.getUserMapByIds(userIds);
		Map<Integer, UserSimple> userMap=BaseClientResult.getResultData(userResult,new HashMap<>());

		IPage<BehaviorSearchModel> data = page.convert(new Function<UserThumbsUpInfo, BehaviorSearchModel>() {
			@Override
			public BehaviorSearchModel apply(UserThumbsUpInfo entity) {
				BehaviorSearchModel model = BehaviorConvertUtils.getBehaviorSearchModel(entity,userMap);
				return model;
			}
		});

		return BaseResult.ok(data);
	}

	@PostMapping("/save")
	@ApiOperation(value="新增",response = String.class)
	public BaseResult save(@RequestBody FollowSaveParam params) {
		ValidatorUtils.validate(params);
		LoginSimpleUserInfo userInfo= AuthContextUtils.getUser();
		UserThumbsUpInfo info= userThumbsUpInfoService.getOne(new QueryWrapper<UserThumbsUpInfo>()
				.eq("user_id", userInfo.getId())
				.eq("obj_type", params.getObjType())
				.eq("obj_no", params.getObjNo())
				.eq("rows_state", BaseConstant.EnabledEnum.ENABLED.getCode())
		);
		if(info!=null) {
			return BaseResult.ok();
		}
		UserThumbsUpInfo entity=new UserThumbsUpInfo();
		entity.setCompanyNo(userInfo.getCompanyNo());
		entity.setUserId(userInfo.getId());
		entity.setObjType(params.getObjType());
		entity.setObjNo(params.getObjNo());
		entity.setObjIsUpdown(BaseConstant.YNEnum.YES.getCode());
		entity.addCreateParam(userInfo);
		userThumbsUpInfoService.save(entity);
		behaviorCacheService.updateThumbsUpCount(params.getObjType(), params.getObjNo(), 1);
		return BaseResult.ok(entity.getId());
	}

	@PostMapping("/cancel")
	@ApiOperation(value="取消",response = String.class)
	public BaseResult cancel(@RequestBody FollowSaveParam params) {
		ValidatorUtils.validate(params);
		LoginSimpleUserInfo userInfo= AuthContextUtils.getUser();
		UserThumbsUpInfo entity= userThumbsUpInfoService.getOne(new QueryWrapper<UserThumbsUpInfo>()
				.eq("user_id", userInfo.getId())
				.eq("obj_type", params.getObjType())
				.eq("obj_no", params.getObjNo())
				.eq("rows_state", BaseConstant.EnabledEnum.ENABLED.getCode())
		);
		if(entity==null) {
			return BaseResult.ok();
		}
		entity.setRowsState(BaseConstant.EnabledEnum.DISABLED.getCode());
		entity.addEditParam(userInfo);
		userThumbsUpInfoService.updateById(entity);
		behaviorCacheService.updateThumbsUpCount(entity.getObjType(), entity.getObjNo(), -1);
		return BaseResult.ok();
	}

	@PostMapping("/isThumbsUp" )
	@ApiOperation(value="当前用户是否点赞",response = String.class)
	public BaseResult isThumbsUp(@RequestBody FollowSaveParam params) {
		ValidatorUtils.validate(params);
		LoginSimpleUserInfo userInfo= AuthContextUtils.getUser();
		UserThumbsUpInfo favorite= userThumbsUpInfoService.getOne(new QueryWrapper<UserThumbsUpInfo>()
				.eq("user_id", userInfo.getId())
				.eq("obj_type", params.getObjType())
				.eq("obj_no", params.getObjNo())
				.eq("rows_state", BaseConstant.EnabledEnum.ENABLED.getCode())
		);
		if(favorite!=null) {
			return BaseResult.ok(BaseConstant.YNEnum.YES.getCode());
		}
		return BaseResult.ok(BaseConstant.YNEnum.NO.getCode());
	}



	@GetMapping("/delete")
	@ApiOperation(value="删除")
	public BaseResult delete(@RequestParam("id")Integer id) {
		UserThumbsUpInfo entity=userThumbsUpInfoService.getById(id);
		if(null == entity || BaseConstant.EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())) {
			throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
		}
		LoginSimpleUserInfo userInfo= AuthContextUtils.getUser();
		entity.setRowsState(BaseConstant.EnabledEnum.DISABLED.getCode());
		entity.addEditParam(userInfo);
		userThumbsUpInfoService.updateById(entity);
		behaviorCacheService.updateThumbsUpCount(entity.getObjType(), entity.getObjNo(), -1);
		return BaseResult.ok();
	}

}
